//
//  ViewController.swift
//  2-08-实战演练
//
//  Created by 范英强 on 16/1/25.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {

    var persons: [Person]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData { (result) -> () in
            //保存数据
            self.persons = result
            //更新ui
            self.tableView.reloadData()
            
        }
        
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let destinationViewController = segue.destinationViewController as!DetailViewController
        let indexPath = tableView.indexPathForSelectedRow!
        destinationViewController.person = persons![indexPath.row]
    }
    
        
        
}
// MARK: - 加载数据
extension ViewController{
    
    func loadData(callback:(result:[Person])->()){
        
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            
            var tempArray = [Person]()
            //模拟耗时操作
            for i in 0..<50 {
                let name = "老王\(i)"
                //arc4random()（在Swift中,可以使用的但是没有智能提示）
                //random()
                //比较 arc4random 性能比random要差一点
                //但是 random有一个bug  每次启动起来的生成随机数都是一样的
                let age =  15 + random()%16
                let p = Person(dict: ["name": name,"age": age])
                tempArray.append(p)
            }
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                //回调
                callback(result: tempArray)
            })
        }
    }
}
//Swift中的extension和OC中的分类相似
//代码分块
extension ViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return persons?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PersonCell
       // cell.textLabel?.text = persons![indexPath.row].name
        cell.person = persons![indexPath.row]
        return cell
}
    
    
    
    
}



